import os
import json
import openpyxl
from tkinter import messagebox

def get_password_value(sn_value):

    # ACHG1821C900
    try:
        with open('config.json', 'r', encoding='utf-8') as config_file:
            config = json.load(config_file)
    except FileNotFoundError:
        messagebox.showerror("错误", "配置文件未找到！")
        return
    
    password_folder_path = config.get("password_folder_path")
    password_row = config.get("password_row")
    
    # 检查值是否为空
    if not password_folder_path or not password_row:
        messagebox.showerror("错误", "路径或行号为空！")
        return

    # 遍历文件夹中的所有xlsx文件
    for filename in os.listdir(password_folder_path):
        if filename.endswith('.xlsx'):
            file_path = os.path.join(password_folder_path, filename)
            try:
                workbook = openpyxl.load_workbook(file_path, data_only=True)
                sheet = workbook.active

                # 查找sn_value所在的行
                for row in sheet.iter_rows():
                    if row[0].value == sn_value:  # 假设sn_value在第一列
                        # 取password_row列的值
                        password_value = row[password_row - 1].value  # 减1是因为索引从0开始
                        if password_value is None:
                            messagebox.showinfo("信息", "密码值为空！")
                        else:
                            messagebox.showinfo("信息", f"密码值: {password_value}")
                        return

            except Exception as e:
                messagebox.showerror("错误", f"读取文件 {filename} 时出错: {e}")

    messagebox.showinfo("信息", "未找到对应的sn_value！")
